﻿/*
    Copyright (C) 2008, wj2929, wj2929@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    *KEEP THIS HEADER INFORMATION*
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mjRegister.BAL;
using mjRegister.Entity;
using System.Threading;
using System.Text.RegularExpressions;

namespace mjRegister
{
    public partial class CarMarket : Form
    {
        private User _user;
        private CarAction _carTradeWay;
        private CarInfo _carInfo;
        private IList<CarInfo> _carInfos;
        private ParkInfo _parkInfo;

        private Form2 _ownerForm;
        IList<Thread> lstThread = new List<Thread>();

        bool cartradeflag = false;
        private ListViewColumnSorter lvwColumnSorter;

        public CarMarket(ParkInfo parkInfo, CarAction carTradeWay, User user,Form2 ownerForm) 
            : this(parkInfo,carTradeWay,new List<CarInfo>(),user,ownerForm)
        {
            //_parkInfo = parkInfo;

            //_carTradeWay = carTradeWay;

            //_user = user;

            //_ownerForm = ownerForm;

            //InitializeComponent();
            //lvwColumnSorter = new ListViewColumnSorter(0, 2);
            //this.listView1.ListViewItemSorter = lvwColumnSorter;

        }
        public CarMarket(ParkInfo parkInfo, CarAction carTradeWay, IList<CarInfo> carInfos, User user, Form2 ownerForm)
        {
            _parkInfo = parkInfo;

            _carTradeWay = carTradeWay;

            if(carInfos.Count > 0)
                _carInfo = carInfos[0];

            _carInfos = carInfos;

            _user = user;

            _ownerForm = ownerForm;

            InitializeComponent();

            lvwColumnSorter = new ListViewColumnSorter(0, 2);
            this.listView1.ListViewItemSorter = lvwColumnSorter;
        }

        public CarMarket(ParkInfo parkInfo, CarAction carTradeWay, CarInfo carInfo, User user,Form2 ownerForm)
            : this(parkInfo, carTradeWay, new List<CarInfo>{carInfo}, user, ownerForm)
        {

        }

        IList<CarMarketInfo> carMarketInfos = new List<CarMarketInfo>();

        delegate void DInit();
        void Init()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));
            this.Invoke(new DSetStatusText(SetStatusText), "正在进行车市数据初始化，请稍等……");
            IList<CarMarketInfo> carMarketInfos = _user.FetchCarMarketInfos(2);
            BAL.CarMarket.Init(carMarketInfos);
            this.Invoke(new DLoadCarMarketData(LoadCarMarketData), carMarketInfos);
            this.Invoke(new DSetStatusText(SetStatusText), "车市数据初始化完成！");
            this.Invoke(new DRestoreControlEnabled(RestoreControlEnabled));
        }

        delegate void DSetStatusText(string text);
        void SetStatusText(string text)
        {
            this.label4.Text = text;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(Init));
            t.Start();
            lstThread.Add(t);
        }

        delegate void DSetControlDisabled();
        void SetControlDisabled()
        {
            this.button1.Enabled = false;
            this.button2.Enabled = false;
            this.comboBox1.Enabled = false;
            this.listView1.Enabled = false;
            this.groupBox1.Enabled = false;
            this.listView2.Enabled = false;
        }

        delegate void DRestoreControlEnabled();
        void RestoreControlEnabled()
        {
            this.button1.Enabled = true;
            this.button2.Enabled = true;
            this.comboBox1.Enabled = true;
            this.listView1.Enabled = true;
            this.groupBox1.Enabled = true;
            this.listView2.Enabled = true;
        }

        delegate void DLoadCarMarketData(IList<CarMarketInfo> carMarketInfos);

        void LoadCarMarketData(IList<CarMarketInfo> carMarketInfos)
        {
            //if (_carTradeWay == CarAction.换购新车)
            //    this.label3.Text = string.Format("当前待换购车：{0}", string.Format("{0}(价值：{1})", _carInfo.car_name, _carInfo.price.ToString()));

            if (_carTradeWay == CarAction.换购新车)
            {
                this.Text = "车市---换购新车";

                string re = ".*?-(?<color>\\d+).gif";
                for (int i = 0; i < _parkInfo.CarInfos.Count; i++)
                {
                    CarInfo carInfo = _parkInfo.CarInfos[i];

                    string color = "未获取";

                    try
                    {
                        if (Regex.IsMatch(carInfo.car_logo_big, re))
                        {
                            color = Regex.Match(carInfo.car_logo_big, re).Result("${color}");
                            color = ((CarColor)int.Parse(color)).ToString();
                        }
                    }
                    catch
                    {
                        color = "未获取";
                    }
                    ListViewItem listViewItem = new ListViewItem(
                        new string[]{
                        (i+1).ToString(),
                        carInfo.carid.ToString(),
                        string.Format("{0}，{1}，{2}",carInfo.car_name,color,carInfo.park_profit.ToString()),
                        carInfo.price.ToString()
                    });

                    if (_carInfos.Where(c => c.carid == carInfo.carid).Count() > 0)
                        listViewItem.Checked = true;

                    listViewItem.Tag = carInfo;

                    this.listView2.Items.Add(listViewItem);
                }
            }
            else
            {
                this.Text = "车市---买车";
                this.panel2.Visible = false;
                this.panel1.Location = new Point(this.panel1.Location.X, this.panel2.Location.Y);
                this.Height -= 200;
            }
            this.label2.Text = string.Format("[我的汽车]数据：车({0})：{1} 现金：{2} 总金额：{3}",
                _parkInfo.CarInfos.Count.ToString(),
                _parkInfo.ParkAmountInfo.AllCarAmount.ToString(),
                _parkInfo.ParkAmountInfo.Cash.ToString(),
                _parkInfo.ParkAmountInfo.TotalAmount.ToString());

            this.comboBox1.Items.Clear();

            Common.FillDropDownList(this.comboBox1, typeof(CarColor));
            if (this.comboBox1.Items.Count > 0)
                this.comboBox1.SelectedIndex = 0;

            this.button2.Text = _carTradeWay.ToString();

            this.listView1.Items.Clear();

            for (int i = 0; i < carMarketInfos.Count; i++)
            {
                CarMarketInfo carMarketInfo = carMarketInfos[i];

                ListViewItem listViewItem = new ListViewItem(
                    new string[]{
                        carMarketInfo.CarId.ToString(),
                        carMarketInfo.CarName,
                        carMarketInfo.CarPrice.ToString()
                    });

                listViewItem.Tag = carMarketInfo;

                this.listView1.Items.Add(listViewItem);
            }
        }

        private void CarMarket_Load(object sender, EventArgs e)
        {
            carMarketInfos = BAL.CarMarket.GetCarMarketInfos();

            if (carMarketInfos.Count > 0)
            {
                LoadCarMarketData(carMarketInfos);
                this.label4.Text = "完成车市数据加载！";
            }
            else
                this.label4.Text = "未找到车市数据，请先初始化！";
        }

        delegate void DAppendText(string text);

        private void button2_Click(object sender, EventArgs e)
        {
            IList<CarMarketInfo> carMarketInfos = new List<CarMarketInfo>();
            
            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                ListViewItem listViewItem = this.listView1.Items[i];
                if (listViewItem.Checked)
                    carMarketInfos.Add((CarMarketInfo)listViewItem.Tag);
            }


            if (carMarketInfos.Count > 0)
            {
                CarMarketInfo carMarketInfo = (CarMarketInfo)carMarketInfos[0];

                if (_carTradeWay == CarAction.买车)
                {
                    if (_parkInfo.ParkAmountInfo.Cash == 0 || _parkInfo.ParkAmountInfo.Cash >= carMarketInfo.CarPrice)
                    {
                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                         string.Format("[{0}]：[{1}]买车：",
                             DateTime.Now.ToString("HH:mm:ss"),
                               string.Format("{0},{1}", _user.UserInfo.uid, _user.UserInfo.real_name)));

                        string purchaseCarMessage = Park.PurchaseCar(_parkInfo.Verify, carMarketInfo.CarId.ToString(), ((int)Enum.Parse(typeof(CarColor), this.comboBox1.Text)).ToString());

                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                             string.Format("[{0}]：[{1}]：{2}\n",
                                 DateTime.Now.ToString("HH:mm:ss"),
                                   string.Format("{0},{1}", _user.UserInfo.uid, _user.UserInfo.real_name),
                                   purchaseCarMessage.Replace("\n","")));

                        cartradeflag = true;

                        MessageBox.Show(purchaseCarMessage);
                    }
                    else
                        MessageBox.Show("您的现金不够！");
                }
                else
                {
                    IList<CarInfo> carInfos = GetSelectCarInfos().OrderByDescending(c => c.price).ToList();
                    if (carInfos.Count == 0)
                    {
                        MessageBox.Show("请选择需要换购的车辆！");
                        return;
                    }
                    if (carInfos.Count > 6)
                    {
                        MessageBox.Show("换购同一车型不能超过6辆！");
                    }
                    else
                    {
                        this.Invoke(new DAppendText(_ownerForm.AppendText),
                             string.Format("[{0}]：[{1}]换购新车：",
                                 DateTime.Now.ToString("HH:mm:ss"),
                                   string.Format("{0},{1}", _user.UserInfo.uid, _user.UserInfo.real_name)));

                        StringBuilder sbMessage = new StringBuilder();

                        for (int i = 0; i < carInfos.Count; i++)
                        {
                            string updateCarMessage = Park.UpdateCar(_parkInfo.Verify, 
                                carInfos[i].carid.ToString(), 
                                carMarketInfo.CarId.ToString(), 
                                ((int)Enum.Parse(typeof(CarColor),carInfos.Count == 1 ? this.comboBox1.Text : this.comboBox1.Items[i].ToString())).ToString());

                            this.Invoke(new DAppendText(_ownerForm.AppendText),
                                 string.Format("[{0}]：[{1}]：{2}\n",
                                     DateTime.Now.ToString("HH:mm:ss"),
                                       string.Format("{0},{1}", _user.UserInfo.uid, _user.UserInfo.real_name),
                                       updateCarMessage.Replace("\n", "")));

                            cartradeflag = true;

                            sbMessage.AppendLine(string.Format("{0}:{1}", carInfos[i].car_name,updateCarMessage));
                        }
                        MessageBox.Show(sbMessage.ToString());
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                }
            }
            else
            {
                MessageBox.Show("尚未在车市选择汽车！");
            }
        }

        private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                ListViewItem listViewItem = this.listView1.Items[i];
                if (i != e.Index)
                    listViewItem.Checked = false;
            }
        }

        private void CarMarket_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
            if (cartradeflag)
                this.DialogResult = DialogResult.OK;

        }

        public void Stop()
        {
            lstThread = lstThread.Where(t => t.IsAlive).ToList();

            if (lstThread.Count > 0)
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：正在中断当前执行线程……",
                        DateTime.Now.ToString("HH:mm:ss")));

                for (int i = 0; i < lstThread.Count; i++)
                {
                    lstThread[i].Abort();
                }

                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：中断当前执行线程完成！\n",
                        DateTime.Now.ToString("HH:mm:ss")));
            }
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (this.listView1.CheckedItems.Count > 0)
            {
                ListViewItem listViewItem = this.listView1.CheckedItems[0];
                this.label5.Text = string.Format("当前选择车辆：{0}，{1}，{2}", listViewItem.SubItems[1].Text, this.comboBox1.Text, listViewItem.SubItems[2].Text);
            }
            else
                this.label5.Text = "当前未选择车辆！";
        }

        IList<CarInfo> GetSelectCarInfos()
        {
            IList<CarInfo> carInfos = new List<CarInfo>();
            for (int i = 0; i < this.listView2.Items.Count; i++)
            {
                ListViewItem item = this.listView2.Items[i];
                if(item.Checked)
                    carInfos.Add((CarInfo)item.Tag);
            }
            return carInfos;
        }

        CarMarketInfo IntellectSelectCar(IList<CarMarketInfo> carMarketInfos, CarAction carAction, ParkInfo existParkInfo, bool selectCheap,bool selectTeam)
        {
            CarMarketInfo selectCarMarketInfo = new CarMarketInfo();
            IList<string> existCarName = existParkInfo.CarInfos.Select(c => c.car_name).ToList();
            IList<CarMarketInfo> cmis = carMarketInfos.Where(c => !existCarName.Contains(c.CarName)).ToList();
            switch (carAction)
            {
                case CarAction.买车:
                    if(cmis.Count > 0)
                    {
                        selectCarMarketInfo = cmis[0];
                        bool find_select_car_flag = false;
                        for(int i=0; i<cmis.Count; i++)
                        {
                            if (selectCarMarketInfo.CarPrice < existParkInfo.ParkAmountInfo.Cash && cmis[i].CarPrice < existParkInfo.ParkAmountInfo.Cash)
                            {
                                selectCarMarketInfo = selectCheap ? (selectCarMarketInfo.CarPrice > cmis[i].CarPrice ? cmis[i] : selectCarMarketInfo) : selectCarMarketInfo.CarPrice < cmis[i].CarPrice ? cmis[i] : selectCarMarketInfo;
                                find_select_car_flag = true;
                            }
                        }
                        if (!find_select_car_flag)
                            selectCarMarketInfo = new CarMarketInfo();
                    }
                    break;
                case CarAction.换购新车:
                    if (!selectTeam)
                    {
                        IList<CarInfo> selectCarInfos = GetSelectCarInfos();
                        if (selectCarInfos.Count == 1)
                        {
                            _carInfo = selectCarInfos[0];
                            CarMarketInfo curUpdateMarketInfo = carMarketInfos.Single(c => c.CarName == _carInfo.car_name);
                            for (int i = 0; i < cmis.Count; i++)
                            {
                                CarMarketInfo carMarketInfo = cmis[i];
                                selectCarMarketInfo = selectCheap ?
                                    (carMarketInfo.CarPrice < (selectCarMarketInfo.CarId == 0 ? curUpdateMarketInfo : selectCarMarketInfo).CarPrice ? carMarketInfo : selectCarMarketInfo.CarId == 0 ? carMarketInfo : selectCarMarketInfo) :
                                        ((carMarketInfo.CarPrice > curUpdateMarketInfo.CarPrice && carMarketInfo.CarPrice < curUpdateMarketInfo.CarPrice + _parkInfo.ParkAmountInfo.Cash) ?
                                            carMarketInfo : selectCarMarketInfo.CarId == 0 ? curUpdateMarketInfo : selectCarMarketInfo);
                            }
                        }
                        else if (selectCarInfos.Count > 1)
                        {
                            int carprice = selectCarInfos.Sum(c => c.price);
                            IList<CarInfo> noSelectCarInfos = _parkInfo.CarInfos.Where(c => !GetArray<int>.Get(selectCarInfos.Select(cc => cc.carid).ToList()).Contains(c.carid)).ToList();
                            IList<CarMarketInfo> fitCarMarketInfos = selectCheap ? carMarketInfos.Where(c => c.CarPrice > 200000).OrderBy(c => c.CarPrice).ToList() : carMarketInfos.Where(c => c.CarPrice > 200000).OrderByDescending(c => c.CarPrice).ToList();
                            for (int i = 0; i < fitCarMarketInfos.Count; i++)
                            {
                                CarMarketInfo carMarketInfo = fitCarMarketInfos[i];
                                int thesamecarnum = selectCarInfos.Where(c => c.car_name == carMarketInfo.CarName).Count();
                                int money = carprice + _parkInfo.ParkAmountInfo.Cash + thesamecarnum * carMarketInfo.CarPrice;
                                if (money > carMarketInfo.CarPrice * selectCarInfos.Count)
                                {
                                    selectCarMarketInfo = carMarketInfo;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        IList<CarMarketInfo> fitCarMarketInfos = selectCheap ? carMarketInfos.Where(c => c.CarPrice > 200000).OrderBy(c => c.CarPrice).ToList() : carMarketInfos.Where(c => c.CarPrice > 200000).OrderByDescending(c => c.CarPrice).ToList();

                        IList<CarInfo> needSelectCarInfos = new List<CarInfo>();

                        //if (selectCheap)
                        //    needSelectCarInfos = _parkInfo.CarInfos.OrderBy(c => c.price).Skip(0).Take(6).ToList();
                        //else
                            needSelectCarInfos = _parkInfo.CarInfos.OrderByDescending(c => c.price).Skip(0).Take(6).ToList();
                        
                        int needSelectCarInfosPrice = needSelectCarInfos.Sum(c => c.price);

                        CheckListView2(needSelectCarInfos);

                        for (int i = 0; i < fitCarMarketInfos.Count; i++)
                        {
                            CarMarketInfo carMarketInfo = fitCarMarketInfos[i];
                            if (needSelectCarInfosPrice + _parkInfo.ParkAmountInfo.Cash > carMarketInfo.CarPrice * 6)
                            {
                                selectCarMarketInfo = carMarketInfo;

                                break;
                            }
                        }
                    }

                    break;
            }
            return selectCarMarketInfo;
        }

        void CheckListView2(IList<CarInfo> carInfos)
        {
            for (int i = 0; i < this.listView2.Items.Count; i++)
            {
                ListViewItem item = this.listView2.Items[i];
                CarInfo carInfo = (CarInfo)item.Tag;
                if (carInfos.Where(c => c.carid == carInfo.carid).Count() > 0)
                    item.Checked = true;
                else
                    item.Checked = false;
            }
        }

        private void radioButton_MouseClick(object sender, MouseEventArgs e)
        {
            if (_parkInfo.ParkAmountInfo.Cash != 0)
            {
                CarMarketInfo carMarketInfo = new CarMarketInfo();
                RadioButton rb = (RadioButton)sender;
                switch (rb.Name)
                {
                    case "radioButton1":
                        carMarketInfo = IntellectSelectCar(carMarketInfos, _carTradeWay, _parkInfo, false,false);
                        break;
                    case "radioButton2":
                        carMarketInfo = IntellectSelectCar(carMarketInfos, _carTradeWay, _parkInfo, true,false);
                        break;
                    case "radioButton3":
                        if (_parkInfo.CarInfos.Count >= 6)
                            carMarketInfo = IntellectSelectCar(carMarketInfos, _carTradeWay, _parkInfo, false, true);
                        else
                        {
                            MessageBox.Show("您的汽车不足6辆，不能辅助选择！");
                            return;
                        }
                        break;
                    case "radioButton4":
                        if (_parkInfo.CarInfos.Count >= 6)
                            carMarketInfo = IntellectSelectCar(carMarketInfos, _carTradeWay, _parkInfo, true, true);
                        else
                        {
                            MessageBox.Show("您的汽车不足6辆，不能辅助选择！");
                            return;
                        }
                        break;
                }
                if (carMarketInfo.CarPrice > 0)
                {
                    if (_carInfo != null && carMarketInfo.CarName == _carInfo.car_name)
                        this.label5.Text = "未能找到合适车辆！";
                    else
                    {
                        this.listView1.Items[carMarketInfo.Index].Checked = false;
                        this.listView1.Items[carMarketInfo.Index].Checked = true;
                    }
                        
                }
                else
                    this.label5.Text = "未能找到合适车辆！";
            }
            else
                MessageBox.Show("现金为0时不能辅助选择车辆。");

        }

        void aa(object obj)
        {
            bb bb = (bb)obj;
            CarMarketInfo carMarketInfo = (CarMarketInfo)bb.CarMarketInfo;

            Console.WriteLine(Park.PurchaseCar(_parkInfo.Verify, carMarketInfo.CarId.ToString(), ((int)Enum.Parse(typeof(CarColor), bb.color)).ToString()));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            IList<CarMarketInfo> carMarketInfos = new List<CarMarketInfo>();

            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                ListViewItem listViewItem = this.listView1.Items[i];
                if (listViewItem.Checked)
                    carMarketInfos.Add((CarMarketInfo)listViewItem.Tag);
            }

            CarMarketInfo carMarketInfo = carMarketInfos[0];

            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                bb bb = new bb
                {
                    color = this.comboBox1.Items[i].ToString(),
                    CarMarketInfo = carMarketInfo
                };
                Thread t = new Thread(new ParameterizedThreadStart(aa));
                t.Start(bb);
                lstThread.Add(t);
            }
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // 检查点击的列是不是现在的排序列.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // 重新设置此列的排序方法.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // 用新的排序方法对ListView排序
            this.listView1.Sort();

        }

        private void listView2_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //int itemCheckedNum = 0;
            //for (int i = 0; i < this.listView2.Items.Count; i++)
            //{
            //    ListViewItem item = this.listView2.Items[i];
            //    itemCheckedNum += item.Checked ? 1 : 0;
            //}
            //this.radioButton1.Enabled = !(itemCheckedNum > 1);
            //this.radioButton2.Enabled = !(itemCheckedNum > 1);
            //this.button2.Enabled = !(itemCheckedNum == 0);
        }

        private void listView2_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            int itemCheckedNum = 0;
            for (int i = 0; i < this.listView2.Items.Count; i++)
            {
                ListViewItem item = this.listView2.Items[i];
                itemCheckedNum += item.Checked ? 1 : 0;
            }
            this.numericUpDown1.Enabled = this.checkBox1.Enabled = this.radioButton2.Enabled = this.radioButton1.Enabled = !(itemCheckedNum > 1);
            //this.radioButton2.Enabled = !(itemCheckedNum > 1);
            this.button2.Enabled = !(itemCheckedNum == 0);
        }
    }

    public class bb
    {
        public string color { get; set; }
        public CarMarketInfo CarMarketInfo { get; set; }
    }
}
